<template>
  <section>
    <!--高级查询工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getEmployeesPlus">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--数据展示列表,展示的数据是domain中的字段-->
    <el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="80" sortable>
      </el-table-column>
      <el-table-column prop="password" label="密码" width="330" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template scope="scope">
          <span style="color: #5daf34" v-if="scope.row.state === 1">启用</span>
          <span style="color:red" v-else-if="scope.row.state === 0">禁用</span>
          <span style="color:dimgrey" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="80" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="220" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="140" sortable>
      </el-table-column>
      <el-table-column prop="department_id" label="部门id" width="90" sortable>
      </el-table-column>
<!--      <el-table-column prop="logininfo_id" label="登录id" width="90" sortable>
      </el-table-column>
      <el-table-column prop="shop_id" label="shopid"  width="90" sortable>
      </el-table-column>-->
      <el-table-column label="操作" width="180" align="center">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页+批量删除工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="sizes, prev, pager, next, jumper, total"
          @current-change="handleCurrentChange"
          @size-change="sizeChange"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :pager-count="pagerCount"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增或编辑界面-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="editForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="editForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门id">
          <!--
             :key   下拉列表行的唯一键 id，有几个不同的id就会有几个下拉选项，如果id相同，会覆盖前一个
             :label  选中之后展示在下拉列表框中的值
             :value  选中之后绑定给模型层的
             value-key="id"  如果我们要传递对象给后端，这里一定增加value-key

          -->
          <el-select v-model="editForm.department_id" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in departments"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="盐值" prop="salt">
          <el-input v-model="editForm.salt" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="登录信息" prop="logininfo_id">
          <el-input v-model="editForm.logininfo_id" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="shop" prop="shop_id">
          <el-input v-model="editForm.shop_id" auto-complete="off"></el-input>
        </el-form-item>-->
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, editEmployee, addEmployee } from '../../api/api';

export default {
  data() {
    return {
      filters: {
        keyword: ''
      },
      title:"",
      departments:[],
      employees:[],//所有员工，用于查询员工管理员
      total: 0,
      currentPage: 1,
      pageSize:4,
      pagerCount:5,//页码超过5时折叠后续页码，用...显示
      pageSizes:[1,2,4,8,10,20,50],//每页展示条数下拉框候选项
      listLoading: false,
      sels: [],//列表选中行
      //编辑界面是否显示
      editFormVisible: false,
      editLoading: false,
      //校验规则
      editFormRules: {
        username: [
            /*
            * required：必填
            * trigger：触发条件
            * blur：失去焦点
            * */
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ]
      },
      //在编辑界面可能要显示以下数据
      editForm: {
        id:"",
        username:"",
        password:"",
        state:"",
        age:"",
        email:"",
        phone:"",
        department_id:"",
        salt:"",
        logininfo_id:"",
        shop_id:""
      }
    }
  },
  methods: {
    //页面展示数据条数变化时重新查询
    sizeChange(size){
      this.pageSize=size
      this.getEmployeesPlus();
    },
    //页码变化时重新查询
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getEmployees();
    },
    //给高级查询单独搞一个方法
    getEmployeesPlus(){
      //高级查询完成之后，需要定位页码到第一页
      this.currentPage=1
      this.getEmployees()
    },
    //获取员工列表
    getEmployees() {
      //封装高级查询+分页的参数
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.filters.keyword
      };
      this.listLoading = true;
      this.$http.post("/employee",para)
      .then(result=>{
        //关闭忙等列表
        this.listLoading = false;
        //得到的就是PageList
        result=result.data;
        this.total=result.total;
        this.employees=result.rows;
      })
      .catch(result=>{
        console.log(result);
        this.$message({
          message: '系统繁忙，稍后重试！',
          type: 'error'
        });
      })
    },
    //获取所有部门信息
    getDepartments(){
      this.$http.get("/dept")
      .then(result=>{
        this.departments=result.data;
      })
    },
    //删除一个
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => {
        //确定要删除
        this.listLoading = true;
        //发起删除请求
        this.$http.delete("/employee/"+row.id)
        .then(result=>{
          console.log(result)
          this.listLoading = false;
          result=result.data//AjaxResult
          if(!result.success){
            this.$message({
              message: result.message,
              type: 'error'
            });
          }
          //删除成功
          this.$message({
            message: result.message+"离谱",
            type: 'success'
          });
          //数据删除成功后要定位到第一页
          this.currentPage = 1;
          this.getEmployees();
        })
        .catch(result=>{
          //后台删除失败
          this.$message({
            message: '系统繁忙，稍后重试！',
            type: 'error'
          });
        })
      }).catch(() => {
        //取消或者关闭弹窗
        this.$message({
          message: '取消或者关闭弹窗！',
          type: 'info'
        });
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title="编辑";
      //弹出修改模态框
      this.editFormVisible = true;
      //克隆本行数据到一个新的对象，用于回显
      //如果不克隆直接修改row的话，由于表单中的属性和模型层是双向绑定的，会直接修改页面展示数据，但实际上数据库没有改变，页面刷新就失效
      this.editForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function () {
      this.title="新增";
      //弹出修改模态框
      this.editFormVisible = true;
      this.editForm = {
        //重置表单
        id:null,
        username:"",
        password:"",
        state:null,
        age:null,
        email:"",
        phone:"",
        department_id:null,
        salt:"",
        logininfo_id:null,
        shop_id:null
      };
    },
    //新增或者编辑
    editSubmit: function () {
      //this.$refs 拿到当前页面上的所有ref
      //this.$refs.editForm  找editForm
      this.$refs.editForm.validate((valid) => {//主动开启表单校验
        if (valid) {//如果校验没有问题
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //开启按钮忙等
            this.editLoading = true;
            let para = Object.assign({}, this.editForm);
            //发起请求保存数据
            this.$http.put("/employee",para)
                .then(result=>{
                  //关闭按钮忙等
                  this.editLoading = false;
                  result=result.data//AjaxResult
                  if(result.success){
                    //后端操作成功
                    this.$message({
                      message: result.message,
                      type: 'success'
                    });
                    //关闭模态框
                    this.editFormVisible = false;
                  }else{
                    this.$message({
                      message: result.message,
                      type: 'error'
                    });
                  };
                  //重新查询所有数据
                  this.getEmployeesPlus()
                })
                .catch(result=>{
                  //操作失败
                  this.$message({
                    message: result.data.message,
                    type: 'error'
                  });
                })
          }).catch(() => {
            //提交界面点击取消
            this.$message({
              message:"操作取消",
              type: 'info'
            });
          });
        }
      });
    },
    //批量删除选中多行时
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      //得到要删除的数据的id数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //前端发送批量删除的请求
        this.$http.patch("/employee",ids)
        .then(result=>{
          this.listLoading = false;
          this.$message({
            message: "删除成功",
            type: 'success'
          });
          this.getEmployeesPlus()
        })
        .catch(result=>{
          this.$message({
            message: result.data.message,
            type: 'error'
          });
        })
      }).catch(() => {
        console.log("quxiaoshanchu")
            this.$message({
              message:"已经取消删除",
              type: 'info'
            });
      });
    },
  },
  mounted() {
    this.getEmployees();
    this.getDepartments();
  }
}

</script>

<style scoped>

</style>